package org.loda.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.loda.exception.InitDbConnectionException;

public class DBConnection {

	private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {

		@Override
		protected Connection initialValue() {
			String driver = ConfigReader.getString("driver");
			String url = ConfigReader.getString("url");
			String user = ConfigReader.getString("user");
			String password = ConfigReader.getString("password");
			try {
				Class.forName(driver);
				return DriverManager.getConnection(url, user, password);
			} catch (Exception e) {
				throw new InitDbConnectionException("数据库初始化失败", e);
			}
		}

	};

	public static Connection getConnection() {
		return connectionHolder.get();
	}
	
	public static void close(){
		try {
			Connection conn=getConnection();
			if(conn!=null){
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void close(PreparedStatement ps) {
		close(ps, null);
	}

	public static void close(PreparedStatement ps, ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (ps != null)
					ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} 
		}
	}

}
